// components/search/module/sShop/sShop.js
import api from "../../../../api/index";
const { debounce } = require("../../../../utils/util");
Component({
  options: {
    // virtualHost: true,
    styleIsolation: "apply-shared",
  },
  /**
   * 组件的属性列表
   */
  properties: {
    data: {
      type: Object,
      value: () => {
        return {};
      },
    },
    value: {
      type: String | Number,
      value: "",
    },
    show: {
      type: Boolean,
      value: false,
    },
  },
  attached() {
    this.getProvince();
    this.getShopList()
  },
  observers: {
    value(v) {
      this.setData({
        pValue: v || 0,
      });
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    area: '',
    show: false,
    areaShow: false,
    insideValue: "",
    pValue: 0,
    list: [],
    options: [],
    searchVal: ''
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onClose() {
      this.triggerEvent("close");
    },
    onSearch: debounce(function (e) {
      this.setData({
        searchVal: e.detail.value,
        list: this.data.data.list.filter(
          (i) => i.shop_name.indexOf(e.detail.value) !== -1
        ),
      });
    }, 500),
    changeVal(e) {
      this.setData({
        pValue: this.data.list[e.currentTarget.dataset.index].shop_id,
      });
    },
    getProvince() {
      let recursion = (list) => {
        return list.map((item) => {
          let obj = {
            text: item.title,
            value: item.title,
          };
          if (item.junior) obj.children = recursion(item.junior);
          return obj;
        });
      };
      api.apiStoreProvince().then((res) => {
        let list = recursion(res.data);
        this.setData({
          options: list,
        });
      });
    },
    openArea() {
      this.setData({
        areaShow: true,
      });
    },
    areaClose() {
      this.setData({
        areaShow: false,
      });
    },
    areaFinish(e) {
      let selectedOptions = e.detail.selectedOptions
      this.getShopList(selectedOptions[0].value, selectedOptions[1].value, selectedOptions[2].value)
      this.setData({
        area: selectedOptions[0].value + '/' + selectedOptions[1].value + '/' + selectedOptions[2].value,
        areaShow: false,
      });
    },
    getShopList(province, city, district) {
      let data = {};
      if (province) data.province = province;
      if (city) data.city = city;
      if (district) data.district = district;
      api.apiStoreShopList(data).then((res) => {
        this.setData({
          list: res.data.list,
        });
      });
    },
    getValue(e) {
      this.triggerEvent("value", {
        type: this.data.data.name,
        value: this.data.pValue,
      });
    },
  },
});
